﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.Threading;

namespace _0812045
{
    public class GameplayScreen : GameScreen
    {
        #region Fields

        ContentManager content;

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }

        CharacterManager charman = new CharacterManager();
        MapManager mapManager = new MapManager();
        List<Character> _character;
        Tank tank;
        Map map;
        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        MousePointer mousePointer;
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            tank = new Tank();
            tank.Init(content, 1, "tank");
            /////Load MousePointer//////
            Texture2D[] mousePic = new Texture2D[8];
            for (int i = 0; i < 8; i++)
                mousePic[i] = content.Load<Texture2D>(@"MousePointer/target"+ i.ToString("00"));
            mousePointer = new MousePointer(ScreenManager._game);
            mousePointer.PointerTexture = mousePic;
            mousePointer.DrawOrder = 1000;
            mousePointer.RestrictZone = new Rectangle(0, 0, ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height);
            ScreenManager._game.Components.Add(mousePointer);
            ///////////////////////////
            charman.InitPrototypes(content);
            mapManager.InitPrototypes(content);
            _character = new List<Character>();
            //_character.Add(new Character());
            //_character[0] = (Character)charman.CreateObject(0);
            //_character[0].x = 0;
            //_character[0].y = 0;

            map = (Map)mapManager.CreateObject(0);
            // A real game would probably have more content than this sample, so
            // it would take longer to load. We simulate that by delaying for a
            // while, giving you a chance to admire the beautiful loading screen.
            Thread.Sleep(1000);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();
        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
            ScreenManager._game.Components.Remove(mousePointer);
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you tab away to a different application.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
            map.Update(gameTime);
            if (IsActive)
            {
                for (int i = 0; i < _character.Count; i++)
                    _character[i].Update(gameTime);
            }
            tank.Update(gameTime);
        }


        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        int iDelay = 0;
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            // Look up inputs for the active player profile.
            int playerIndex = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            // The game pauses either if the user presses the pause button, or if
            // they unplug the active gamepad. This requires us to keep track of
            // whether a gamepad was ever plugged in, because we don't want to pause
            // on PC if they are playing with a keyboard and have no gamepad at all!
            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       input.GamePadWasConnected[playerIndex];

            if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
            {
                ScreenManager.AddScreen(new PauseMenuScreen(ScreenManager), ControllingPlayer);
            }
            else
            {
                // Otherwise move the player position.
                //Vector2 movement = Vector2.Zero;

                //if (keyboardState.IsKeyDown(Keys.Z) && iDelay == 0)
                //    tank.Fire(bulletManager);

                ////if (keyboardState.IsKeyDown(Keys.Right))
                ////    movement.X++;

                //if (keyboardState.IsKeyDown(Keys.Up))
                //    _character[0].y -= 10;

                //if (keyboardState.IsKeyDown(Keys.Down))
                //    _character[0].y += 10;

                //Vector2 thumbstick = gamePadState.ThumbSticks.Left;

                //movement.X += thumbstick.X;
                //movement.Y -= thumbstick.Y;

                //if (movement.Length() > 1)
                //    movement.Normalize();

                //playerPosition += movement * 2;
            }
        }


        /// <summary>
        /// Draws the gameplay screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            // Our player and enemy are both actually just text strings.
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin();
            for (int i = 0; i < _character.Count; i++)
                _character[i].Draw(gameTime, spriteBatch);

            map.Draw(gameTime, spriteBatch);
            tank.Draw(gameTime, spriteBatch);
            spriteBatch.End();

            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha);
        }


        #endregion
    }
}
